///////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2008  
// Authors: Aljosa Osep (aljosa.osep@gmail.com), Jernej Kranjec (jernej.kranjec@gmail.com)
// From Faculty of Electrical Engineering and Computer Science, Maribor, Slovenia
// Done at School of Technology, Seinajoki, Finland
// Under mentor Kimmo Salmenjoki (kimmo.salmenjoki@seamk.fi)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace DeviceApplication1
{
    public partial class SocketClient : Form
    {
     //   byte[] m_dataBuffer = new byte[10];
     //   IAsyncResult m_result;
     //   public AsyncCallback m_pfnCallBack;
        public Socket m_clientSocket;

        public SocketClient()
        {
            InitializeComponent();
            textBoxIp.Text = getDeviceIp();
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (textBoxIp.Text == "" || textBoxPort.Text == "")
            {
                MessageBox.Show("You must enter IP and port.");
                return;
            }
            try
            {
                m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // create socket instance

                IPAddress ip = IPAddress.Parse(textBoxIp.Text); // get remote ip and parse it
           //     MessageBox.Show(ip.ToString());
                int port = System.Convert.ToInt16(textBoxPort.Text); // port number

                // create end point
                IPEndPoint endPoint = new IPEndPoint(ip, port);

                // connect to remote host
                m_clientSocket.Connect(endPoint);

                if (m_clientSocket.Connected)
                {
                    labelStatus.Text = "Status (Mono): connected";
          //          WaitForData(); // wait asinhronosly  // !!!
                }
            }
            catch(SocketException se) // tmp, change excpetion to socket!
            {
                MessageBox.Show("Error connecting: " + se.Message);
            }
        } 

        private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            if (m_clientSocket != null)
            {
                m_clientSocket.Close();
                m_clientSocket = null;
            }

        }


        private void buttonSend_Click(object sender, EventArgs e)
        {
            try
            {
                Object data = textBoxMessage.Text;
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(data.ToString());

                if (m_clientSocket != null)
                {
                    m_clientSocket.Send(byData);
                }
            }
            catch (SocketException se)
            {
                MessageBox.Show("Error sending: " + se.Message);
            }
        }

        ///////////////////////////
        // Gets ip of device 
        ////////////////////////////
        String getDeviceIp()
        {
            String hostName = Dns.GetHostName();

            // find host by name
            IPHostEntry hostEntry = Dns.GetHostEntry(hostName);

            // grab first ip address
            String ip_string = "";
            foreach (IPAddress ipaddr in hostEntry.AddressList)
            {
                ip_string = ipaddr.ToString();
                return ip_string;
            }
            return ip_string;
        }




    }
}